package com.nj9you.sdk.dlg;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nj9you.sdk.params.PayParams;
import com.nj9you.sdk.pay.IPay;
import com.nj9you.sdk.utils.Log;
import com.nj9you.sdk.utils.Utils;

import java.io.File;
import java.util.List;

/**
 * 订单详情对话框
 */

public class OrderDetailDialog extends Dialog implements View.OnClickListener, DialogInterface.OnDismissListener, AdapterView.OnItemClickListener {
    private static final String WXPAY_PLUGIN_PKGNAME = "com.nj9you.wxpay"; // 微信支付插件的包名

    private PayParams mPayParams;
    private IPay mPay;
    private OnConfirmPayListener mOnConfirmPayListener;
    private View mProgressBar;
    private Handler mHandler;
    private boolean mHasFocus;
    private List<IPay> mPayList;
    private IPay mDefaultPay;
    private ListView mListView;
    private PayAdapter mPayAdapter;
    private TextView mProductName;
    private TextView mPayAmount;
    private TextView mPayAmountTip;

    public OrderDetailDialog(Context context, PayParams params, IPay iPay, List<IPay> iPayList, int theme) {
        super(context, theme);
        mPayParams = params;
        mDefaultPay = iPay;
        mPay = iPay;
        mPayList = iPayList;
        setCanceledOnTouchOutside(false);
        mHandler = new Handler();
        setOnDismissListener(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(Utils.getLayoutId(getContext(), "jy_dialog_orderdetail"));
        initView();
        initData();
    }

    private void initView() {
        mProgressBar = findViewById(Utils.getId(getContext(), "progressbar"));
        mProgressBar.setVisibility(View.GONE);
        mListView = (ListView) findViewById(Utils.getId(getContext(), "pay_list"));
        View back = findViewById(Utils.getId(getContext(), "back_btn"));
        back.setOnClickListener(this);
        mProductName = (TextView) findViewById(Utils.getId(getContext(), "product_name"));
        mPayAmount = (TextView) findViewById(Utils.getId(getContext(), "pay_amount"));
        mPayAmountTip = (TextView) findViewById(Utils.getId(getContext(), "pay_amount_tip"));
        Button payButton = (Button) findViewById(Utils.getId(
                getContext(), "order_detail_pay"));
        payButton.setOnClickListener(this);

        if (mPayParams != null) {
        }
    }

    private void initData() {
        int size = mPayList.size();
        mListView.setChoiceMode(GridView.CHOICE_MODE_SINGLE);
        mListView.setOnItemClickListener(this);

        mPayAdapter = new PayAdapter(getContext(), mPayList);
        mListView.setAdapter(mPayAdapter);
        if (mDefaultPay != null) {
            mListView.setItemChecked(findDefaultPosition(), true);
        }
        mProductName.setText(mPayParams.getSubject());
        String priceAmount = getContext().getString(Utils.getStringId(getContext(), "jy_payamount"), Utils.convertFenToYuan(mPayParams.getPrice()));
        mPayAmount.setText(priceAmount);
        updatePayAmountTip();
    }

    private void updatePayAmountTip() {
        String priceAmount = Utils.convertFenToYuan(mPayParams.getPrice());
        String payTip = getContext().getString(Utils.getStringId(getContext(), "jy_payamount_tip"), priceAmount);
        Utils.highLightText(mPayAmountTip, payTip, priceAmount);
    }

    private int findDefaultPosition() {
        int len = mPayList.size();
        for (int i = 0; i < len; i++) {
            if (mDefaultPay.getPayType() == mPayList.get(i).getPayType()) {
                return i;
            }
        }
        return -1;
    }

    private void installWxPayPlugin() {
        Toast.makeText(getContext(), "请先安装两宇科技控件再进行支付",
                Toast.LENGTH_SHORT).show();
        File file = new File(getContext().getCacheDir(), "wxpay-plugin.apk");
        Utils.copyAssets(getContext(), "wxpay-plugin.apk", file.getAbsolutePath());
        if (file.exists()) {
            // 设置读权限
            file.setReadable(true, false);
        }
        Utils.showInstallActivity(getContext(), file.getAbsolutePath());
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == Utils.getId(getContext(), "back_btn")) {
            cancel();
        } else if (v.getId() == Utils.getId(getContext(), "order_detail_pay")) {
            if (mPay != null && mPay.getPayType() == IPay.PAY_TYPE_WECHATPAY) {
                String signStr = Utils.getSign(getContext(), WXPAY_PLUGIN_PKGNAME);
                if (TextUtils.isEmpty(signStr)) {
                    installWxPayPlugin();
                    return;
                }
            }
            if (mOnConfirmPayListener != null) {
                // 开始支付时，禁止认为关闭对话框
                v.setEnabled(false);
                setCancelable(false);
                mProgressBar.setVisibility(View.VISIBLE);
                mProgressBar.requestFocus();
                mOnConfirmPayListener.onConfirmPay(mPay, mPayParams);
                setOrderDetailDialogCancelableOnTimeout();
            }
        }
    }

    public void setOnConfirmPayListener(OnConfirmPayListener l) {
        mOnConfirmPayListener = l;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        removeCancelableRunnable();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (mPayAdapter != null) {
            mPay = mPayAdapter.getItem(position);
            mPayAdapter.notifyDataSetChanged();
        }
        updatePayAmountTip();
    }

    public interface OnConfirmPayListener {
        public void onConfirmPay(IPay iPay, PayParams payParams);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        mHasFocus = hasFocus;
    }

    /**
     * 超时未出现支付界面，可关闭订单详情
     */
    private void setOrderDetailDialogCancelableOnTimeout() {
        Log.d(Log.TAG, "");
        mHandler.postDelayed(mCancelableRunnable, 10 * 1000);
    }

    private void removeCancelableRunnable() {
        Log.d(Log.TAG, "");
        try {
            mHandler.removeCallbacks(mCancelableRunnable);
        } catch (Exception e) {
        }
    }

    private Runnable mCancelableRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                if (isShowing() && mHasFocus) {
                    Log.d(Log.TAG, "Set dialog cancelable true");
                    setCancelable(true);
                }
            } catch (Exception e) {
            }
        }
    };

    public class PayAdapter extends ArrayAdapter<IPay> {

        public PayAdapter(Context context, List<IPay> objects) {
            super(context, 0, objects);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(Utils.getLayoutId(getContext(), "jy_pay_item_layout"), new RelativeLayout(getContext()));
                holder = new ViewHolder();
                holder.payIcon = (ImageView) convertView.findViewById(Utils.getId(getContext(), "pay_icon"));
                holder.payName = (TextView) convertView.findViewById(Utils.getId(getContext(), "pay_name"));
                holder.payDesc = (TextView) convertView.findViewById(Utils.getId(getContext(), "pay_desc"));
                holder.paySelect = (ImageView) convertView.findViewById(Utils.getId(getContext(), "select_pay"));
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            IPay ipay = getItem(position);
            holder.payIcon.setImageResource(ipay.getPayIcon());
            holder.payName.setText(ipay.getPayName());
            holder.payDesc.setText(ipay.getPayDesc());
            if (mListView.isItemChecked(position)) {
                holder.paySelect.setVisibility(View.VISIBLE);
            } else {
                holder.paySelect.setVisibility(View.GONE);
            }
            return convertView;
        }

        class ViewHolder {
            public ImageView payIcon;
            public TextView payName;
            public TextView payDesc;
            public ImageView paySelect;
        }
    }
}
